/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kreig133.spine.builder;

import com.kreig133.builder.ParametrsForBuild;
import com.kreig133.spine.simplemodel.SimpleEvent;
import com.kreig133.spine.simplemodel.SimpleExperiment;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author eshangareev
 */
class ExperimentBuilder {

    protected ParametrsForBuild parametrsForBuild;
    protected SimpleExperiment experiment;
    protected List<SimpleEvent> events;

    public ExperimentBuilder(ParametrsForBuild parametrsForBuild) {
        this.parametrsForBuild = parametrsForBuild;
    }

    public void createExperiment() {
        try {
            Map<String, String> parametrs = parametrsForBuild.getParametrs().remove(0);
            String clazzName = parametrs.remove("class");
            Class clazz = Class.forName(clazzName);
            experiment = (SimpleExperiment) clazz.newInstance();
            setParametrsToObject(experiment, parametrs);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void createEvents() {
        try {
            events = new ArrayList<SimpleEvent>();
            for (Map<String, String> map : parametrsForBuild.getParametrs()) {
                SimpleEvent current = new SimpleEvent();
                setParametrsToObject(current, map);
                events.add(current);
                current = null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected void setParametrsToObject(Object object, Map<String, String> parametrs) {
        try {
            Method[] methods = object.getClass().getMethods();
            for (String key : parametrs.keySet()) {
                for (Method m : methods) {
                    if (m.getName().toLowerCase().equals("set" + key)) {
                        m.invoke(object,
                                m.getParameterTypes()[0].getConstructor(String.class).newInstance(parametrs.get(key)));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public SimpleExperiment getBuildedExperiment(){
        experiment.setEvents(events);
        return experiment;
    }
}
